const md5 = require("./md5.js");
let timer;

function request(url, method, params, header) {
  header = header || {};
  timer = setTimeout(() => {
    wx.showLoading({})
  }, 500)
  setTimeout(() => {
    wx.hideLoading()
  }, 1000);
  let time = new Date().getTime();
  let uid = wx.getStorageSync('uid') ? wx.getStorageSync('uid') : 0;
  let token = wx.getStorageSync('token') ? wx.getStorageSync('token') : 0;
  let lastParams = `?uid=${uid}&time=${time}&secret=${md5.hexMD5('71clouddangjiang' + token + time + uid)}`;
  url += lastParams;
  return new Promise((resolve, reject)=>{
    wx.request({
      url: url,
      data: params || {},
      method: method || 'get',
      header: header,
      success: (res) => {
        clearTimeout(timer);
        wx.hideLoading();
        if(res.data.code==1){
          //res.data 就是后台的返回的数据
          resolve(res.data)
        }else if(res.data.code==0){
          if (res.data.msg) {
            wx.showToast({
              title: res.data.msg,
              icon: 'none',
            })
          } else {
            wx.showToast({
              title: res.data.data,
              icon: 'none',
            })
          }
        }else if (res.data.code == 2) {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
          })
        } else if (res.data.code == 3) {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
          })
        }else if (res.data.code == 4) {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
          })
        }else if(res.data.code==8){
          resolve(res.data)
        }
      },
      fail: (err) => {
        clearTimeout(timer);
        wx.hideLoading();
        wx.showToast({
          title: '网络异常，请重试',
          icon: 'none',
          duration: 2000
        });
        reject(err)
      }
    });
  })
}

export const ajax = {
  get: (url, params) => {
    return request(url, 'get', params, {'content-type': 'application/json'})
  },
  post: (url, params) => {
    return request(url, 'post', params, {'content-type': 'application/x-www-form-urlencoded'})
  }
};
